package com.xiaoq.social.repository.impl;

import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xiaoq.coms.util.IdGenerator;
import com.xiaoq.social.entity.LikeitEntity;
import com.xiaoq.social.repository.ILikeitRepository;
@Repository
public class LikeitRepositoryImpl implements ILikeitRepository {
	
	@Autowired
	private Datastore datastore;
	
	@Autowired
	private IdGenerator idGenerator;
	
	private static final Logger LOG = LoggerFactory.getLogger(LikeitRepositoryImpl.class);

	@Override
	public boolean isLikeit(String userId, String tgtId) {
		Query<LikeitEntity> likeitQuery = datastore.createQuery(LikeitEntity.class);
		if(StringUtils.isNotEmpty(tgtId)&&StringUtils.isNotEmpty(userId)){
			LikeitEntity likeit = likeitQuery.field("userId").equal(userId).field("targetId").equal(tgtId).get();
			if(likeit!=null){
				LOG.info(userId+"已经点赞"+tgtId);
				return true;
			}else{
				LOG.info(userId+"未点赞"+tgtId);
			}
			
		}else{
		LOG.error("tgtId或者userId不能为空会报空指针异常！");
		}
		return false;
	}

	@Override
	public boolean addLikeit(LikeitEntity likeit) {
		if(likeit!=null){
			String id = idGenerator.nextId();
			likeit.setId(id);
			LOG.info("点赞的Id:"+id);
			datastore.save(likeit);
			return true;
		}else{
			LOG.error("LikeitEntity 值传入为空！");
		}
		return false;
	}

	@Override
	public boolean delLikeit(String userId, String tgtId) {
		Query<LikeitEntity> likeitQuery = datastore.find(LikeitEntity.class);
		if(StringUtils.isNotEmpty(userId)&&StringUtils.isNotEmpty(tgtId)){
			likeitQuery.field("userId").equal(userId).field("targetId").equal(tgtId);
			datastore.delete(likeitQuery);
			return true;
		}
		return false;
	}

	@Override
	public Long getTgtNums(String tgtId) {
		Query<LikeitEntity> likeitQuery = datastore.find(LikeitEntity.class);
		Long tgtLikeitNums = 0L;
		if(StringUtils.isNoneEmpty(tgtId)){
			likeitQuery.field("targetId").equal(tgtId);
			tgtLikeitNums = likeitQuery.count();
		}
		return tgtLikeitNums;
	}
	
	

}
